#include "box.h"
#include <QStringList>
#include <QDebug>
#include "defs.h"

const QString Box::m_rxText = QString("(\\w+)");
const QString Box::m_rxNumber = QString("(\\d+)");
const QRegExp Box::m_rxName = QRegExp(QString("\\b%1\\b").arg(m_rxText));
const QRegExp Box::m_rxDesc = QRegExp(QString("\\{%1\\}").arg(m_rxText));
const QRegExp Box::m_rxCount = QRegExp(QString("\\[%1\\]").arg(m_rxNumber));
const QRegExp Box::m_rxSorts = QRegExp("\\((.*)\\)");
const QRegExp Box::m_rxDateTime = QRegExp("\\<(.+)\\>");

Box::Box()
{
}

Box::Box(const QString &str)
{
    m_items.clear();
    parse(str);
}

QString Box::boxName() const
{
    return m_boxName;
}

void Box::setBoxName(const QString &newName)
{
    m_boxName = newName;
}

int Box::itemsTotal() const
{
    return m_items.count();
}

QString Box::itemName(int itemIdx) const
{
    if (isValidIdx(itemIdx))
        return m_items[itemIdx].info.name;
    return QString();
}

int Box::itemCount(int itemIdx) const
{
    if (isValidIdx(itemIdx))
        return m_items[itemIdx].info.count;
    return -1;
}

QString Box::itemDesc(int itemIdx) const
{
    if (isValidIdx(itemIdx))
        return m_items[itemIdx].info.desc;
    return QString();
}

QDateTime Box::itemDateTime(int itemIdx) const
{
    if (isValidIdx(itemIdx))
        return m_items[itemIdx].info.dateTime;
    return QDateTime();
}

void Box::parse(const QString &str)
{
    QStringList items = str.split(';', QString::SkipEmptyParts);
    foreach (QString item, items)
        parseItem(item);
}

void Box::parseItem(const QString &str)
{
    m_items.push_back(BoxItem());
    BoxItem &item = m_items[m_items.count() - 1];

    if (m_rxSorts.indexIn(str) != -1) {
        qDebug() << "has sorts";
        int bracket = str.indexOf('(');
        qDebug() << str.left(bracket);
        parseNameDescCountDate(str.left(bracket), item.info);
        QStringList sorts = m_rxSorts.cap(1).split(",,", QString::SkipEmptyParts);
        item.sorts.clear();
        for (int i = 0; i < sorts.count(); ++i) {
            item.sorts.push_back(BoxItemData());
            parseNameDescCountDate(sorts[i], item.sorts[i]);
        }
    } else {
        parseNameDescCountDate(str, item.info);
    }
}

void Box::parseNameDescCountDate(const QString &str, BoxItemData &itemData)
{
    if (m_rxName.indexIn(str) != -1)
        itemData.name = m_rxName.cap(1);
    if (m_rxDesc.indexIn(str) != -1)
        itemData.desc = m_rxDesc.cap(1);
    if (m_rxCount.indexIn(str) != -1)
        itemData.count = m_rxCount.cap(1).toInt();
    else
        itemData.count = -1;
    if (m_rxDateTime.indexIn(str) != -1)
        itemData.dateTime = QDateTime::fromString(m_rxDateTime.cap(1), BOX_DATETIME_FORMAT);
}

bool Box::isValidIdx(int idx) const
{
    return idx >= 0 && idx < m_items.count();
}
